/**
 * 链地址法
 *
 * @author fireway
 *
 */
public class HashChainTable {
    private SortedList[] mHashArray;

    private int mHashArraySize;

    public HashChainTable(int size) {
        mHashArraySize = size;
        mHashArray = new SortedList[mHashArraySize];

        for (int i = 0; i < mHashArraySize; i++) {
            mHashArray[i] = new SortedList();
        }
    }

    private int hashFunc(int key) {
        return key % mHashArraySize;
    }

    public void insert(Node node) {
        int key = node.getKey();
        int hash = hashFunc(key);

        mHashArray[hash].insert(node);
    }


    public boolean delete(int key) {
        boolean ret = false;
        int hash = hashFunc(key);
        ret = mHashArray[hash].delete(key);
        return ret;
    }

    public Node find(int key) {
        int hash = hashFunc(key);
        Node ret = mHashArray[hash].find(key);
        return ret;
    }

    public void displayAddress() {
        for (int i = 0; i < mHashArraySize; i++) {
            String s = String.format("%3s", i);
            System.out.print(s + ". ");
            mHashArray[i].displayAddress();
            System.out.print("\n");
        }
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder();

        for (int i = 0; i < mHashArraySize; i++) {
            String s = String.format("%3s", i);
            b.append(s + ". ");
            b.append(mHashArray[i]);
            b.append("\n");
        }

        return b.toString();
    }
}

